package cn.qixin.passport.service.impl;

import cn.qixin.passport.service.IUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class UploadServiceImpl implements IUploadService {

    @Value("${dirPath}")
    private String dirPath;

    @Override
    public String upload(MultipartFile pic) {
        //得到唯一文件名
        String fileName = pic.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        //准备文件夹
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //准备文件的完整路径
        String filePath = dirPath+"/images/"+fileName;
        System.out.println("图片保存路径"+new File(filePath).getAbsoluteFile());

        try {
            pic.transferTo(new File(filePath).getAbsoluteFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://localhost:9091/images/"+fileName;
    }
}
